﻿using System;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using static Ev_ExcelStandard.Models;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using ExcelDataReader;
using System.Data;

namespace Ev_ExcelStandard
{
    public class EvExcelConvertStrings
    {
        public EvExcelConvertStrings()
        {
        }


        #region iOS Language File

        public static void saveLanguageFile(string filePath, string content)
        {
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            //文本读取器
            using (FileStream fs = new FileStream(filePath, FileMode.CreateNew))
            {
                //【2】保存内容到txt
                StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
                sw.WriteLine(content);
                sw.Flush();
                sw.Close();
            }
        }

        /// <summary>
        /// 设置iOS语言包文件值
        /// </summary>
        /// <param name="content"></param>
        /// <param name="list"></param>
        public static string setLanguageContent(string content, List<modelKeyValue> list)
        {

            List<modelLanguageKeyValueStr> listModel = new List<modelLanguageKeyValueStr>();
            var languageList = content.Split("\";");
            foreach (var strLanguage in languageList)
            {
                var model = new modelLanguageKeyValueStr();
                model.strLanguage = strLanguage;

                var keyValue = strLanguage.Split("=");
                if (keyValue.Length != 2)
                {
                    // 如果有多个 = 等号存在
                    // 后面再写
                    continue;
                }
                model.strKey = keyValue[0].Trim();
                model.strValue = keyValue[1].TrimStart();
                listModel.Add(model);
            }

            foreach (var dict in list)
            {
                var model = listModel.Find(x => {
                    return x.strKey == $"\"{dict.strKey}\"";
                });
                /// 如果已存在Key ，则替换
                if (model != null)
                {
                    var oldStrValue = $"{model.strValue}";
                    var newStrValue = $"\"{dict.strValue}";
                    var newStrReplace = model.strLanguage.Replace(oldStrValue, newStrValue);
                    content = content.Replace(model.strLanguage, newStrReplace);
                }
                else
                {
                    /// 否则新增
                    content += $"\n\"{dict.strKey}\" = \"{dict.strValue}\";";
                }
            }

            return content;
        }

        /// <summary>
        /// 读取iOS语言包文件内容
        /// </summary>
        /// <param name="strLanguagePath"></param>
        /// <returns></returns>
        public static string readLanguageFile(string strLanguagePath)
        {

            if (!File.Exists(strLanguagePath))
            {
                return "";
            }
            //文本读取器
            using (TextReader reader = new StreamReader(strLanguagePath, System.Text.Encoding.UTF8))
            {
                var strLocalizableStr = "";
                //一次性读完
                strLocalizableStr = reader.ReadToEnd();
                return strLocalizableStr;
            }

        }

        #endregion

        #region Excel

        /// <summary>
        ///  获取Excel 文件
        /// </summary>
        /// <param name="excelPath"></param>
        /// <returns></returns>
        public static ISheet readExcel(string excelPath)
        {
            if (!File.Exists(excelPath))
            {
                return null;
            }
            using (var stream = new FileStream(excelPath, FileMode.Open))
            {
                stream.Position = 0;
                var pathExtension = Path.GetExtension(excelPath);
                if (pathExtension == ".xlsx")
                {
                    XSSFWorkbook workbook = new XSSFWorkbook(stream);  // .xlsx
                    ISheet sheet = workbook.GetSheetAt(0);
                    return sheet;
                }
                else if (pathExtension == ".xls")
                {
                    HSSFWorkbook workbook = new HSSFWorkbook(stream);    // .xls
                    ISheet sheet = workbook.GetSheetAt(0);
                    return sheet;
                }
            }
            return null;
        }

        /// <summary>
        /// 获取指定的KeyValue的语言包数据
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="keyId"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static List<modelKeyValue> readSheet(ISheet sheet, string keyId, string value)
        {

            List<modelKeyValue> list = new List<modelKeyValue>();

            IRow headerRow = sheet.GetRow(0);
            int cellCount = headerRow.LastCellNum;

            var cellKeyIdIndex = headerRow.Cells.FindIndex(x => x.ToString() == keyId);
            var cellKeyValueIndex = headerRow.Cells.FindIndex(x => x.ToString() == value);
            //var cccc = headerRow.Cells.FindIndex(x => x.ToString() == "asddasd");
            if (cellKeyIdIndex < 0 || cellKeyValueIndex < 0)
            {
                Console.WriteLine("Excel keyId 或 语言Value 的title值错误，请重新开始转换流程");
                return null;
            }

            // 开始获取每一行的数据
            for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
            {
                IRow row = sheet.GetRow(i);
                if (row == null) continue;


                var strKey = row.Cells[cellKeyIdIndex].ToString();
                if (cellKeyValueIndex > row.Cells.Count - 1)
                {
                    continue;
                }
                var strValue = row.Cells[cellKeyValueIndex].ToString();

                if (string.IsNullOrWhiteSpace(strValue)) continue;

                modelKeyValue dict = new modelKeyValue
                {
                    strKey = strKey,
                    strValue = strValue
                };
                list.Add(dict);
            }
            return list;
        }


        #endregion

        #region loadMac 

        /// <summary>
        ///  获取Excel 文件
        /// </summary>
        /// <param name="excelPath"></param>
        /// <returns></returns>
        public static List<modelKeyValue> readExcelDataMac(string excelPath, string keyId, string value)
        {
            


            //var sheet = readExcel(excelPath);
            //if (sheet == null)
            //{
            //    return null;
            //}

            //var listModel = readSheet(sheet, keyId, value);
            return null;
        }

        #endregion
    }
}

